package com.uxsino.simo.indicator.retractor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.uxsino.commons.utils.config.ConfigProp;

// index count from right, start from 1
// example:
// get full line as record: col_id=-1#-1
// get left few item num >=5: col_id=-1#5
// get only one item: col_id=3
// get range: col_id=6#2

public class CSVReverseRangeRetractor extends CSVListRetractor {
    private static final Logger logger = LoggerFactory.getLogger(CSVReverseRangeRetractor.class);

    @ConfigProp(name = "column_padding", trim = false)
    public String columnPadding;

    public CSVReverseRangeRetractor() {
        super();
        columnPadding = " ";
    }

    @Override
    protected String getFieldString(String index, String[] record) {
        String[] indexArr = index.split("#");
        if (indexArr.length < 1 || indexArr.length > 2) {
            logger.error("col_id is not in correct format {}", index);
            return null;
        }
        int[] indexNum = new int[indexArr.length];
        for (int j = 0; j < indexArr.length; j++) {
            try {
                indexNum[j] = Integer.parseInt(indexArr[j]);
            } catch (NumberFormatException e) {
                logger.error("col_id {} did not match format int#int or int", index, e);
                return null;
            }
            if (indexNum[j] < -1 || indexNum[j] == 0 || indexNum[j] > record.length) {
                logger.error("col_id {} is out of range", index);
                return null;
            }
        }

        if (indexArr.length == 1) {
            return record[record.length - indexNum[0]];
        } else {
            int left = indexNum[0] == -1 ? 0 : record.length - indexNum[0];
            int right = indexNum[1] == -1 ? record.length - 1 : record.length - indexNum[1];
            if (right == left) {
                return record[right];
            }
            StringBuilder sb = new StringBuilder();
            for (int j = left; j < right; j++) {
                sb.append(record[j]);
                sb.append(columnPadding);
            }
            sb.append(record[right]);
            return sb.toString();
        }

    }
}
